using System;
using System.Collections.Generic;
using System.Threading;

namespace OracleInternal.Common
{
	internal class TableColumnsCache
	{
		private Dictionary<Tuple<string, string, string>, OracleLpTableColumns> tableColumnsCache = new Dictionary<Tuple<string, string, string>, OracleLpTableColumns>();

		private ReaderWriterLockSlim m_sync_rw = new ReaderWriterLockSlim();

		internal void Put(string serviceName, string schemaName, string tableName, OracleLpTableColumns tableColumns)
		{
			_ = string.Empty;
			if (tableColumnsCache.Count >= ConfigBaseClass.m_ColumnCacheSize)
			{
				string.Concat("Column Cache FULL. Cannot add table columns to cache for service: " + serviceName + ", table: " + tableName + ", Schema: " + schemaName, ", Column Cache Size: ", tableColumnsCache.Count.ToString());
				return;
			}
			Tuple<string, string, string> key = new Tuple<string, string, string>(serviceName, schemaName, tableName);
			if (tableColumnsCache.ContainsKey(key))
			{
				return;
			}
			m_sync_rw.EnterWriteLock();
			try
			{
				if (tableColumnsCache.Count >= ConfigBaseClass.m_ColumnCacheSize || tableColumnsCache.ContainsKey(key))
				{
					return;
				}
				tableColumnsCache.Add(key, tableColumns);
			}
			finally
			{
				m_sync_rw.ExitWriteLock();
			}
			string.Concat("Added table columns to cache for service: " + serviceName + ", table: " + tableName + ", Schema: " + schemaName, ", Column Cache Size: ", tableColumnsCache.Count.ToString());
		}

		internal OracleLpTableColumns Get(string serviceName, string schemaName, string tableName)
		{
			OracleLpTableColumns result = null;
			_ = string.Empty;
			if (tableColumnsCache.Count == 0)
			{
				return result;
			}
			Tuple<string, string, string> key = new Tuple<string, string, string>(serviceName, schemaName, tableName);
			try
			{
				if (tableColumnsCache.ContainsKey(key))
				{
					m_sync_rw.EnterReadLock();
					try
					{
						if (tableColumnsCache.ContainsKey(key))
						{
							result = tableColumnsCache[key];
						}
					}
					finally
					{
						m_sync_rw.ExitReadLock();
					}
					_ = "Found table columns in cache for service: " + serviceName + ", table: " + tableName + ", Schema: " + schemaName;
					return result;
				}
				_ = "Cannot find table columns in cache for service: " + serviceName + ", table: " + tableName + ", Schema: " + schemaName;
				return result;
			}
			catch
			{
				return result;
			}
		}

		internal void Clear()
		{
			m_sync_rw.EnterWriteLock();
			try
			{
				tableColumnsCache.Clear();
			}
			finally
			{
				m_sync_rw.ExitWriteLock();
			}
		}
	}
}
